package com.example.myapplication.data

import com.example.myapplication.model.Stock
import com.example.myapplication.model.StockPrice
import kotlinx.coroutines.delay
import java.util.Calendar
import kotlin.random.Random

/**
 * 股票数据仓库
 * 提供股票列表和历史数据
 */
class StockRepository : IStockRepository {
    
    /**
     * 获取100只优质股票列表
     */
    override suspend fun getPopularStocks(): List<Stock> {
        // 模拟网络延迟
        delay(500)
        
        return QualityStocks.list.map { stockInfo ->
            val basePrice = stockInfo.basePrice
            val change = Random.nextDouble(-5.0, 5.0)
            val changePercent = (change / basePrice) * 100
            val volume = Random.nextLong(50000000, 200000000)
            val marketCap = basePrice * Random.nextDouble(100000000.0, 500000000.0)
            
            Stock(
                symbol = stockInfo.code,
                name = stockInfo.name,
                currentPrice = basePrice + change,
                change = change,
                changePercent = changePercent,
                volume = volume,
                marketCap = marketCap,
                sector = stockInfo.industry
            )
        }
    }
    
    /**
     * 获取股票历史价格数据（周线）
     * 生成模拟的周K线数据用于技术分析
     * 数据从2025年9月1日开始，一直更新到当前最新一周
     */
    override suspend fun getStockHistory(symbol: String, days: Int): List<StockPrice> {
        // 模拟网络延迟
        delay(800)
        
        val prices = mutableListOf<StockPrice>()
        // 使用100只优质股票的基础价格
        var basePrice = QualityStocks.getBasePrice(symbol)
        
        // 设置起始日期为2025年9月1日（星期一）
        val startCalendar = Calendar.getInstance()
        startCalendar.set(2025, Calendar.SEPTEMBER, 1, 9, 30, 0)
        startCalendar.set(Calendar.MILLISECOND, 0)
        
        // 调整到最近的周一
        while (startCalendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
            startCalendar.add(Calendar.DAY_OF_YEAR, 1)
        }
        
        // 获取当前时间，计算到今天为止有多少周
        val currentCalendar = Calendar.getInstance()
        val startTime = startCalendar.timeInMillis
        val currentTime = currentCalendar.timeInMillis
        
        // 计算从9月1日到现在的周数
        val totalWeeks = ((currentTime - startTime) / (7 * 24 * 60 * 60 * 1000L)).toInt() + 1
        val weeksToGenerate = minOf(totalWeeks, 52) // 最多生成52周（1年）
        
        // 调试日志
        android.util.Log.d("📊周线数据", """
            起始日期: ${java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.CHINA).format(startTime)}
            当前日期: ${java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.CHINA).format(currentTime)}
            计算周数: $totalWeeks
            实际生成: ${weeksToGenerate}周
        """.trimIndent())
        
        // 生成趋势性的周K线数据
        val trend = Random.nextDouble(-0.2, 0.4) // 总体趋势
        val calendar = startCalendar.clone() as Calendar
        
        for (i in 0 until weeksToGenerate) {
            // 每周的时间戳（周一09:30）
            val weekTimestamp = calendar.timeInMillis
            
            // 不生成未来的数据
            if (weekTimestamp > currentTime) {
                android.util.Log.d("📊周线数据", "停止生成：第${i+1}周(${java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.CHINA).format(weekTimestamp)})超过当前时间")
                break
            }
            
            // 周线波动幅度更大
            val weeklyChange = Random.nextDouble(-0.08, 0.08) + trend / weeksToGenerate
            basePrice *= (1 + weeklyChange)
            
            val open = basePrice * (1 + Random.nextDouble(-0.02, 0.02))
            val close = basePrice * (1 + Random.nextDouble(-0.03, 0.03))
            val high = maxOf(open, close) * (1 + Random.nextDouble(0.02, 0.06))
            val low = minOf(open, close) * (1 - Random.nextDouble(0.02, 0.06))
            val volume = Random.nextLong(500000000, 1500000000) // 周成交量更大
            
            prices.add(
                StockPrice(
                    timestamp = weekTimestamp,
                    open = open,
                    high = high,
                    low = low,
                    close = close,
                    volume = volume
                )
            )
            
            // 移到下一周（+7天）
            calendar.add(Calendar.DAY_OF_YEAR, 7)
        }
        
        // 日志：显示实际生成的数据范围
        if (prices.isNotEmpty()) {
            val firstDate = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.CHINA).format(prices.first().timestamp)
            val lastDate = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.CHINA).format(prices.last().timestamp)
            android.util.Log.d("📊周线数据", "✅ 成功生成${prices.size}周数据：$firstDate 至 $lastDate")
        }
        
        return prices
    }
    
    /**
     * 搜索股票
     */
    override suspend fun searchStocks(query: String): List<Stock> {
        delay(300)
        
        val allStocks = getPopularStocks()
        return allStocks.filter { 
            it.symbol.contains(query, ignoreCase = true) || 
            it.name.contains(query, ignoreCase = true)
        }
    }
}

